package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.context.UserContext;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.exception.ServiceException;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.common.enums.ShortLinkServiceErrorCode;
import com.nageoffer.shortlink.admin.mapper.GroupMapper;
import com.nageoffer.shortlink.admin.pojo.dto.req.ShortLinkGroupSaveReqDTO;
import com.nageoffer.shortlink.admin.pojo.dto.req.ShortLinkGroupSortReqDTO;
import com.nageoffer.shortlink.admin.pojo.dto.req.ShortLinkGroupUpdateDTO;
import com.nageoffer.shortlink.admin.pojo.dto.resp.ShortLinkGroupRespDTO;
import com.nageoffer.shortlink.admin.pojo.entity.Group;
import com.nageoffer.shortlink.admin.remote.dto.Resp.ShortLinkGroupCountRespDTO;
import com.nageoffer.shortlink.admin.remote.dto.ShortLinkRemoteService;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.toolkit.RandomStringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService {

    private final GroupMapper groupMapper;
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };

    @Override
    public void saveGroup(ShortLinkGroupSaveReqDTO requestParam) {
        this.saveGroup(UserContext.getUsername(),requestParam);
    }

    @Override
    public void saveGroup(String userName, ShortLinkGroupSaveReqDTO requestParam) {
        //随机生成一个gid，然后判断gid唯一
        String gid;
        do{
            gid = RandomStringUtil.generateRandomString();
        }while(hasGid(gid));
        //利用build去创建一个Group对象
        Group group = Group.builder()
                .username(userName)
                .gid(gid)
                .name(requestParam.getGroupName())
                .sortOrder(0)
                .build();
        //存储group对象
        groupMapper.insert(group);
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        String username = UserContext.getUsername();
        LambdaQueryWrapper<Group> wrapper = Wrappers.lambdaQuery(Group.class)
                .eq(Group::getUsername,username)
                .eq(Group::getDelFlag,0)
                .orderByDesc(Group::getSortOrder,Group::getUpdateTime);
        List<Group> groupList = groupMapper.selectList(wrapper);
        if(groupList == null || groupList.size() < 1)
            throw new ClientException(ShortLinkServiceErrorCode.SAAS_GROUP_NOT_EXIST);
        //TODO 在这里将分组所在的数目加上
        //在groupList中跟据gid来查询每个分组中的分组数目
        //返回的是远程接口调用的Result对象
        //判断远程接口的结果是否合法
        //需要取出来shortLinkCount赋值到ShortLinkGroupRespDTO上
        Result<List<ShortLinkGroupCountRespDTO>> listResult = shortLinkRemoteService.listGroupShortLinkCount(
                groupList.stream().map(Group::getGid).toList()
        );

        if(listResult == null || !listResult.isSuccess() || listResult.getData() == null){
            throw new ServiceException("远程服务调用失败！");
        }
        List<ShortLinkGroupCountRespDTO> countList = listResult.getData();
        List<ShortLinkGroupRespDTO> respDTOS = BeanUtil.copyToList(groupList, ShortLinkGroupRespDTO.class);
        for (ShortLinkGroupRespDTO dto : respDTOS) {
            String gid = dto.getGid();
            countList.stream()
                    .filter(item -> Objects.equals(item.getGid(), gid))
                    .findFirst()
                    .ifPresent(item -> dto.setShortLinkCount(item.getShortLinkCount()));
        }
        return respDTOS ;


    }

    @Override
    public void update(ShortLinkGroupUpdateDTO requestParam) {
        String username = UserContext.getUsername();
        LambdaUpdateWrapper<Group> wrapper = Wrappers.lambdaUpdate(Group.class)
                //TODO 这里修改为用ThreadLocal来填充username
                .eq(Group::getUsername,username)
                .eq(Group::getGid,requestParam.getGid())
                .eq(Group::getDelFlag,0)
                .set(Group::getName,requestParam.getGroupName());
        groupMapper.update(null,wrapper);
    }

    @Override
    public void delete(String gid) {
        String username = UserContext.getUsername();
        LambdaUpdateWrapper<Group> wrapper = Wrappers.lambdaUpdate(Group.class)
                //TODO 这里修改为用ThreadLocal来填充username
                .eq(Group::getUsername,username)
                .eq(Group::getGid,gid)
                .eq(Group::getDelFlag,0)
                .set(Group::getDelFlag,1);
        groupMapper.update(null,wrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        String username = UserContext.getUsername();
        requestParam.forEach(sortReqDTO ->{
            LambdaUpdateWrapper<Group> wrapper = Wrappers.lambdaUpdate(Group.class)
                    //TODO 这里修改为用ThreadLocal来填充username
                    .eq(Group::getUsername,username)
                    .eq(Group::getGid,sortReqDTO.getGid())
                    .eq(Group::getDelFlag,0)
                    .set(Group::getSortOrder,sortReqDTO.getSortOrder());
            groupMapper.update(null,wrapper);
        });
    }

    private boolean hasGid(String gid) {
        LambdaQueryWrapper<Group> wrapper = Wrappers.lambdaQuery(Group.class)
                .eq(Group::getGid,gid);
        Group group = groupMapper.selectOne(wrapper);
        if(group == null)
            return false;
        else
            return true;

    }
}
